package com.gdc.miaosha.controller;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.gdc.miaosha.constants.RedisConstant;
import com.gdc.miaosha.entity.User;
import com.gdc.miaosha.exception.GlobalException;
import com.gdc.miaosha.request.UserModifyPwdRequest;
import com.gdc.miaosha.result.CodeMsg;
import com.gdc.miaosha.result.Result;
import com.gdc.miaosha.service.IUserService;
import com.gdc.miaosha.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.Objects;

import static com.gdc.miaosha.constants.CommonConstant.COOKIE_KEY;
import static com.gdc.miaosha.constants.RedisConstant.EXPIRED_2_DAY;

/**
 * Description: 用户 Controller
 * @author: gdc
 * @date: 2022/4/5
 * @version 1.0
 */
@Api(value = "用户接口")
@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
    private IUserService userService;

	
    @RequestMapping("/info")
    @ResponseBody
    @ApiOperation(value = "获取用户详情信息")
    public Result<User> info(Integer id) {
        return Result.success(userService.getById(id));
    }

    @RequestMapping("/modifyPwd")
    @ResponseBody
    @ApiOperation(value = "修改用户密码")
    public Result<Boolean> modifyPwd(UserModifyPwdRequest request,
                                     @CookieValue(COOKIE_KEY) String token) {
        // step 1 获取用户信息
        User user = userService.getById(request.getId());
        if (Objects.isNull(user)) {
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }

        // step 2 修改用户密码
        String newPwd = SecureUtil.md5(request.getPassword() + user.getSalt());
        User updateUser = new User()
                .setId(user.getId())
                .setPassword(newPwd)
                .setUpdateTime(LocalDateTime.now());
        boolean result = userService.updateById(updateUser);
        if (!result) {
            throw new GlobalException(CodeMsg.PASSWORD_MODIFY_FAIL);
        }

        // step 3 清除用户缓存
        RedisUtil.del(RedisConstant.USER + request.getId());

        // step 4 更新用户Token
        user.setPassword(newPwd);
        RedisUtil.set(RedisConstant.TOKEN_PREFIX + token, JSON.toJSONString(user), EXPIRED_2_DAY);
        return Result.success(result);
    }
    
}
